//
// Created by Tan Ke on 2023/12/24.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char** findOcurrences(char* text, char* first, char* second, int* returnSize)
{
    char** wordList = (char**)malloc(sizeof(char*) * 1024);
    int wordListLen = 0;

    int index = 0;
    while (index < strlen(text)) {
        if (text[index] != ' ') {
            break;
        }
        index += 1;
    }

    char tmpStr[1024] = {0};
    int tmpStrLen = 0;

    while (index <= strlen(text)) {
        if (text[index] != ' ' && text[index] != 0) {
            tmpStr[tmpStrLen] = text[index];
            tmpStrLen += 1;
        } else {
            wordList[wordListLen] = (char*)malloc(sizeof(char) * (tmpStrLen + 1));
            memset(wordList[wordListLen], 0, (tmpStrLen + 1));
            memcpy(wordList[wordListLen], tmpStr, tmpStrLen);
            wordListLen += 1;
            memset(tmpStr, 0, 1024);
            tmpStrLen = 0;
        }
        index += 1;
    }
#if 0
    printf("==========================\n");
    for (int i = 0; i < wordListLen; i ++) {
        printf("%s\n", wordList[i]);
    }
    printf("==========================\n");
#endif

    char** result = (char**)malloc(sizeof(char*) * 1024);
    *returnSize = 0;

    for (int i = 0; i < wordListLen; i ++) {
        if (strlen(wordList[i]) == strlen(first) && strcmp(wordList[i], first) == 0) {
            if (i < wordListLen - 2 && strlen(wordList[i + 1]) == strlen(second) && strcmp(wordList[i + 1], second) == 0) {
                result[*returnSize] = wordList[i + 2];
                *returnSize += 1;
            }
        }
    }

    return result;
}

int main(void)
{
    char* text1 = "lri amaktfpync uyb uyb uyb lri rriralwkw rriralwkw rriralwkw rriralwkw uyb rriralwkw uyb uyb amaktfpync rriralwkw amaktfpync uyb uyb lri uyb rriralwkw amaktfpync amaktfpync rriralwkw";
    int returnSize1 = 0;
    char** answer = findOcurrences(text1, "uyb", "lri", &returnSize1);

    for (int i = 0; i < returnSize1; i ++) {
        printf("%s\n", answer[i]);
    }
    return 0;
}
